import { compile } from '@mdx-js/mdx'
import { MDXProvider } from '@mdx-js/react'
import React, { useState, useEffect } from 'react'

function MdxRenderer({ mdxContent, components }) {
  const [Content, setContent] = useState(null)
  const [error, setError] = useState(null)

  useEffect(() => {
    let isMounted = true

    const compileAndRender = async () => {
      try {
        // 编译 MDX
        const compiled = await compile(mdxContent, {
          outputFormat: 'function-body'
        })

        // 创建执行函数
        const runMdx = new Function('React', `${compiled.value}\nreturn MDXContent;`)

        // 执行并获取组件
        const MdxComponent = runMdx(React)

        if (isMounted) {
          setContent(() => MdxComponent)
        }
      } catch (err) {
        if (isMounted) {
          setError(err)
        }
      }
    }

    compileAndRender()

    return () => {
      isMounted = false
    }
  }, [mdxContent])

  if (error) {
    return <div style={{ color: 'red', padding: '20px' }}>MDX 错误: {error.message}</div>
  }

  if (!Content) {
    return <div style={{ padding: '20px' }}>加载中...</div>
  }

  return (
    <MDXProvider components={components}>
      <Content />
    </MDXProvider>
  )
}

// 使用示例
function App() {
  const mdxContent = `
# Hello MDX!

这是一个简单的 MDX 示例。

<Counter />

普通 **Markdown** 内容。
  `

  const components = {
    Counter: () => {
      const [count, setCount] = useState(0)
      return <button onClick={() => setCount(count + 1)}>点击: {count}</button>
    }
  }

  return (
    <div style={{ padding: '20px' }}>
      <MdxRenderer mdxContent={mdxContent} components={components} />
    </div>
  )
}

export default App
